package com.woniuxy.test_iterator;

import java.util.*;

/**
 * description: TestIterator <br>
 * date: 2022/2/4 4:00 下午 <br>
 * author: shesaifei <br>
 * version: 1.0 <br>
 */

/**
 * 使用Iterator（迭代器）遍历/list/set/map
 */
public class TestIterator {
    public static void main(String[] args) {

        List<String> list = new ArrayList<>();
        list.add("aa");
        list.add("bb");
        list.add("cc");

        //使用iterator遍历list
//        for (Iterator<String> iterator = list.iterator(); iterator.hasNext();){
//           String temp = iterator.next();
//            System.out.println(temp);
//        }
//        testIteratorSet();
        testIteratorMap();
    }

    public static void testIteratorSet() {
        Set<String> set = new HashSet<>();
        set.add("aa");
        set.add("bb");
        set.add("cc");
        //使用iterator遍历list
        for (Iterator<String> iterator = set.iterator(); iterator.hasNext(); ) {
            String temp = iterator.next();
            System.out.println(temp);
        }
    }

    public static void testIteratorMap() {
        Map<Integer, String> map = new HashMap();
        map.put(100, "aa");
        map.put(200, "bb");
        map.put(33, "cc");
        //使用iterator遍历Map

        Set<Map.Entry<Integer, String>> ss = map.entrySet();
        for (Iterator<Map.Entry<Integer, String>> iter = ss.iterator(); iter.hasNext(); ) {
            Map.Entry<Integer, String> temp = iter.next();
            System.out.println(temp.getKey() + "---" + temp.getValue());
        }
        System.out.println("++++++++++");
        //第二种方式遍历Map的方式
        Set<Integer> KeySet = map.keySet();
        for (Iterator<Integer> iter = KeySet.iterator(); iter.hasNext(); ) {
            Integer key = iter.next();
            System.out.println(key + "----" + map.get(key));
        }
    }

}
